package com.th.supcom.pds.phamapply.client.widget.inpharmacyreturn;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.grid.AggregationRenderer;
import com.extjs.gxt.ui.client.widget.grid.AggregationRowConfig;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.SummaryType;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Element;
import com.th.supcom.framework.dict.web.gwt.client.DictComboBox;
import com.th.supcom.framework.dict.web.gwt.client.model.DictModel;
import com.th.supcom.pds.common.client.commom.SimpleMethod;
import com.th.supcom.pds.common.client.model.CodeConstants;
import com.th.supcom.pds.common.enums.InpWithDrawType;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.phamapply.client.model.InpPhamApplyDetailModel;

/**
 * 退药信息面板
 * 
 * @author yzhang
 */
/**
 *
 */
public class NurseReturnGridPanel extends ContentPanel
{
    private Grid <InpPhamApplyDetailModel> m_grid;
    private ListStore <InpPhamApplyDetailModel> m_store;

    /**
     * 构造方法
     * 
     * @param drugReturnAndRefundFields
     * @param drugReturnButtons
     */
    public NurseReturnGridPanel ()
    {
        initUI ();
    }

    /**
     * 初始化界面
     */
    private void initUI ()
    {
        setBorders (false);
        setHeaderVisible (false);
        setLayout (new FitLayout ());
        m_store = new ListStore <InpPhamApplyDetailModel> ();
        final ColumnModel columnModel = createGridHeader ();
        columnModel.addAggregationRow (createAggregationRowConfig ());
        m_grid = new EditorGrid <InpPhamApplyDetailModel> (m_store, columnModel);
        m_grid.setStripeRows (true);
        m_grid.setColumnLines (true);
        m_grid.setBorders (false);
        m_grid.setColumnReordering (true);
        m_grid.getView ().setForceFit (true);
        m_grid.setLoadMask (true);
        m_grid.getView ().setEmptyText ("暂时没有您需要的数据...");
        m_grid.setColumnReordering (true);
        add (m_grid);
        ToolBar toolBar = createColorShow ();
        ContentPanel bottomContainer = new ContentPanel ();
        bottomContainer.setHeaderVisible (false);
        bottomContainer.add (toolBar);
        setBottomComponent (bottomContainer);
    }

    private ColumnModel createGridHeader ()
    {
        final List <ColumnConfig> columns = new ArrayList <ColumnConfig> ();

        ColumnConfig column = new ColumnConfig ();
        SimpleMethod.setColumnConfig (column, "phamName", "药品名称", HorizontalAlignment.LEFT, 200, getPhamNameRenderer ());
        columns.add (column);

        column = new ColumnConfig ();
        SimpleMethod.setColumnConfig (column, "phamSpec", "药品规格", HorizontalAlignment.LEFT, 120, null);
        columns.add (column);

        column = new ColumnConfig ();
        column.setDateTimeFormat (DateTimeFormat.getFormat (CodeConstants.DATE_FORMAT_YYYY_MM_DD_HH_MM));
        SimpleMethod.setColumnConfig (column, "chargeDate", "计价时间", HorizontalAlignment.LEFT, 120, null);
        columns.add (column);

        column = new ColumnConfig ();
        SimpleMethod.setColumnConfig (column, "applyDispensaryName", "执行药房", HorizontalAlignment.LEFT, 120, null);
        columns.add (column);

        column = new ColumnConfig ();
        SimpleMethod.setColumnConfig (column, "applyAmount", "数量", HorizontalAlignment.LEFT, 60,
                                      ClientUtils.renderForNumber ("applyAmount"));
        columns.add (column);

        column = new ColumnConfig ();
        SimpleMethod.setColumnConfig (column, "applyUnitName", "单位", HorizontalAlignment.LEFT, 40, null);
        columns.add (column);

        column = new ColumnConfig ();
        SimpleMethod.setColumnConfig (column, "costs", "金额", HorizontalAlignment.LEFT, 60,
                                      ClientUtils.renderForNumber ("costs"));
        columns.add (column);

        column = new ColumnConfig ();
        SimpleMethod.setColumnConfig (column, "withdrawAmount", "退药数量", HorizontalAlignment.LEFT, 70,
                                      getwithdrawAmountRenderer ());
        column.setEditor (createCellEditor ());
        columns.add (column);

        column = new ColumnConfig ();
        SimpleMethod.setColumnConfig (column, "withdrawTypeName", "退药方式 ", HorizontalAlignment.LEFT, 70,
                                      getwithdrawTypeRenderer ());
        column.setEditor (getDictEditor (new DictComboBox ("PDS0028"), "withdrawType", "N", "无药退药"));
        columns.add (column);

        return new ColumnModel (columns);
    }

    /**
     * 颜色提示
     * 
     * @return
     */
    private ToolBar createColorShow ()
    {
        ToolBar toolBar;
        toolBar = new ToolBar ();
        String txt = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                     + "<span class='redTendGrade'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;不可退药品</spqn> <span class='grayTendGrade'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;可编辑</span>";
        Label lab = new Label (txt);
        lab.setStyleAttribute ("margin-left", "10px");
        toolBar.add (lab);
        return toolBar;
    }

    /**
     * 药品名称列渲染器
     * 
     * @return
     */
    private GridCellRenderer <InpPhamApplyDetailModel> getPhamNameRenderer ()
    {
        final GridCellRenderer <InpPhamApplyDetailModel> change = new GridCellRenderer <InpPhamApplyDetailModel> ()
        {
            @Override
            public Object render (final InpPhamApplyDetailModel model, final String property, final ColumnData config,
                                  final int rowIndex, final int colIndex,
                                  final ListStore <InpPhamApplyDetailModel> store,
                                  final Grid <InpPhamApplyDetailModel> grid)
            {
                if (model.getPhamReturnIndicator () != null)
                {
                    config.cellAttr = "style='background-color:#FF0000; height:16px'";
                }
                else
                {
                    config.cellAttr = "";
                }
                return "<span>" + model.getPhamName () + "</span>";
            }
        };
        return change;
    }

    /**
     * 退药类型列渲染器
     * 
     * @return
     */
    private GridCellRenderer <InpPhamApplyDetailModel> getwithdrawTypeRenderer ()
    {
        final GridCellRenderer <InpPhamApplyDetailModel> change = new GridCellRenderer <InpPhamApplyDetailModel> ()
        {
            @Override
            public Object render (final InpPhamApplyDetailModel model, final String property, final ColumnData config,
                                  final int rowIndex, final int colIndex,
                                  final ListStore <InpPhamApplyDetailModel> store,
                                  final Grid <InpPhamApplyDetailModel> grid)
            {
                if (InpWithDrawType.ReturnWithoutDrug.getEnumCode ().equals (model.getWithdrawConfig ()))
                {
                    config.cellAttr = "style='background-color:#E6E6F2; height:16px'";
                }
                else
                {
                    config.cellAttr = "";
                }
                String withdrawType = model.getWithdrawTypeName ();
                return "<span>" + withdrawType + "</span>";
            }
        };
        return change;
    }

    /**
     * 退药数量列渲染器
     * 
     * @return
     */

    private GridCellRenderer <InpPhamApplyDetailModel> getwithdrawAmountRenderer ()
    {
        final GridCellRenderer <InpPhamApplyDetailModel> change = new GridCellRenderer <InpPhamApplyDetailModel> ()
        {

            @Override
            public Object render (final InpPhamApplyDetailModel model, final String property, final ColumnData config,
                                  final int rowIndex, final int colIndex,
                                  final ListStore <InpPhamApplyDetailModel> store,
                                  final Grid <InpPhamApplyDetailModel> grid)
            {
                config.cellAttr = "style='background-color:#E6E6F2; height:16px'";
                if (null == model.getWithdrawAmount ())
                {
                    return null;
                }
                String withdrawAmount = model.getWithdrawAmount ().toString ();
                return "<span style='float:right'>" + withdrawAmount + "</span>";
            }
        };
        return change;
    }

    /**
     * 编辑退药数量
     * 
     * @return
     */
    private CellEditor createCellEditor ()
    {

        final NumberField numberField = new NumberField ();
        numberField.setAllowNegative (false);
        numberField.setRegex ("^[0-9]*[0-9][0-9]*$");
        numberField.setPropertyEditorType (Integer.class);
        return new CellEditor (numberField)
        {
            @Override
            public Object postProcessValue (Object value)
            {
                InpPhamApplyDetailModel model = m_grid.getStore ().getAt (super.row);
                Integer max = model.getApplyAmount ();
                if (null == numberField.getValue ())
                {
                    return value;
                }
                if (numberField.getValue ().intValue () > max)
                {
                    model.setWithdrawAmount (max);
                    Info.display ("提示", "输入数量不能大于原有数量！");
                    return String.valueOf (model.get ("withdrawAmount"));
                }
                model.setWithdrawAmount (numberField.getValue ().intValue ());
                return String.valueOf (model.get ("withdrawAmount"));
            }

            @Override
            public Object preProcessValue (Object value)
            {
                if (null == value)
                {
                    return value;
                }
                else
                {
                    return Integer.parseInt ((String) value);
                }
            }

        };

    }

    /**
     * 表格grid列--字典下拉框CellEditor
     * 
     * @param grid 表格
     * @param combo 字典ComboBox对象
     * @param property model值字段
     * @param defaultCode 默认字段
     * @param defaultValue 默认字段名称
     * @return
     */
    public CellEditor getDictEditor (final DictComboBox combo, final String property, final String defaultCode,
                                     final String defaultValue)
    {
        final CellEditor editor = new CellEditor (combo)
        {
            @Override
            public void startEdit (final Element el, final Object value)
            {
                if (InpWithDrawType.ReturnWithDrug.getEnumCode ().equals (m_store.getAt (super.row)
                                                                                 .getWithdrawConfig ()))
                {
                    super.hide ();
                    return;
                }
                else
                {
                    super.startEdit (el, value);
                }

            }

            @Override
            public Object postProcessValue (final Object value)
            {
                InpPhamApplyDetailModel model = m_grid.getStore ().getAt (super.row);
                model.set (property, combo.getValue ().getDictItemCode ());
                return combo.getValue ().getDictItemName ();
            }

            @Override
            public Object preProcessValue (final Object value)
            {
                if (value == null)
                {
                    DictModel model = new DictModel ();
                    model.setDictItemCode (defaultCode);
                    model.setDictItemName (defaultValue);
                    return model;
                }

                DictModel dictModel = null;
                for (final DictModel dict : combo.getStore ().getModels ())
                {
                    if (dict.getDictItemName ().equals (value.toString ()))
                    {
                        dictModel = dict;
                        break;
                    }
                }
                combo.setEditable (false);
                return dictModel;
            }

        };
        return editor;
    }

    /**
     * 加载数据
     * 
     * @param models
     */
    public void refresh (List <InpPhamApplyDetailModel> models)
    {
        m_store.removeAll ();
        m_store.add (models);
    }

    public Grid <InpPhamApplyDetailModel> getGrid ()
    {
        return m_grid;
    }

    public ListStore <InpPhamApplyDetailModel> getStore ()
    {
        return m_store;
    }

    /**
     * 获取表格中的models
     * 
     * @return
     */
    public List <InpPhamApplyDetailModel> getModels ()
    {
        return m_store.getModels ();
    }

    private AggregationRowConfig <InpPhamApplyDetailModel> createAggregationRowConfig ()
    {
        final AggregationRowConfig <InpPhamApplyDetailModel> config = new AggregationRowConfig <InpPhamApplyDetailModel> ();
        config.setHtml ("applyUnitName", "合计");
        config.setSummaryType ("costs", SummaryType.SUM);
        config.setRenderer ("costs", new AggregationRenderer <InpPhamApplyDetailModel> ()
        {
            @Override
            public Object render (final Number value, final int colIndex, final Grid <InpPhamApplyDetailModel> grid,
                                  final ListStore <InpPhamApplyDetailModel> store)
            {
                String displayValue = "0.00";
                if (null != value)
                {
                    displayValue = ClientUtils.formatNumTwo ((Double) value);
                }
                return "<span style='color:red;font-weight:bold;'>" + displayValue + "</span>";
            }
        });
        return config;
    }
}
